﻿using System;
using System.Collections.Generic;
using System.Text;
using NetServ.Net.Json;
using System.IO;

namespace GoogleCode.WebTools.Examples
{
    class Json
    {
        public static void ParseJSON(String response)
        {
            // Parse the given JSON response
            JsonParser parser = new JsonParser(new StringReader(response), true);
            JsonObject json = parser.ParseObject();

            // The JSON interface of the called system says the following:
            //
            //     1. The JSON response always has a key called "error" set
            //        to a non-0 value if there's an error
            //     2. In the case there's no error, the JSON response has a
            //        key called "payload"
            if (!json.ContainsKey("error"))
            {
                // This is against the called service's specifications
                throw new InvalidDataException("The JSON response doesn't have any request error state!");
            }
            else if (json["error"].ToString() != "0")
            {
                // The other end has returned an error
                throw new Exception("Error " + json["error"] + ": " + json["errorDescription"]);
            }
            else if (!json.ContainsKey("payload"))
            {
                // This is against the called service's specifications
                throw new InvalidDataException("The JSON response doesn't have any payload!");
            }
            else
            {
                // We got our payload :)
                //
                // The JSON interface of the called system says that
                // the response payload is supposed to be a JSON array
                IJsonType payload = json["payload"];
                if (!(payload is JsonArray))
                {
                    // This is against the called service's specifications
                    throw new InvalidDataException("The JSON payload is not an array!");
                }

                JsonArray names = (JsonArray)payload;
                Console.WriteLine("Found " + names.Count + " people matching your request");
                foreach (IJsonType name in names)
                {
                    Console.WriteLine("\t" + name);
                }
            }
        }
    }
}
